import axios, { AxiosResponse, Canceler } from 'axios'
import http from '@/utils/http'

interface UploadFileReturn {
  request: Promise<AxiosResponse>,
  cancel: Canceler
}

declare type UploadFile = (
  file: File,
  uploadProgress?: (progressEvent: any) => void
) => UploadFileReturn

const uploadFile: UploadFile = (file, uploadProgress) => {
  const data = new FormData()
  data.append('bucketName', 'poros')
  data.append('expireDate', '0')
  data.append('file', file)

  const { token, cancel } = axios.CancelToken.source()

  const request = http.request({
    url: '/poros-oss/file/upload',
    method: 'POST',
    data,
    onUploadProgress: uploadProgress,
    cancelToken: token,
    timeout: 0
  })

  return {
    request,
    cancel
  }
}

export default uploadFile
